package com.kds.changzhou.utility;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author 孔德嵩
 */
@Component
public class TemplateService {

    @Resource
    private Configuration configuration;

    public byte[] buildRequest(Object object) throws IOException, TemplateException {
        return buildTemplate(object, "request.ftlx");
    }

    public byte[] buildMD5(Object object) throws IOException, TemplateException {
        return buildTemplate(object, "md5.ftlx");
    }

    public byte[] buildNotify(Object object) throws IOException, TemplateException {
        return buildTemplate(object, "notify.ftlx");
    }

    public byte[] buildReport(Object object) throws IOException, TemplateException {
        return buildTemplate(object, "report.ftlx");
    }


    private byte[] buildTemplate(Object object, String fileName) throws IOException, TemplateException {

        Template template = configuration.getTemplate(fileName);

        StringWriter stringWriter = new StringWriter();

        template.process(object, stringWriter);

        return stringWriter.toString().getBytes(StandardCharsets.UTF_8);
    }
}
